﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using XfTech.SmartTms.Users.Dtos;

namespace XfTech.SmartTms.Controllers
{
    [ApiController] //所有的API控制器必须要有这个注解
    [Route("api/[controller]/")]
    public class LoginController : SmartTmsController   //必须继承基类
    {
        //控制器的方法
        private readonly IConfiguration _configuration;
        private readonly ILogger<LoginController> _logger; //日志

        public LoginController(IConfiguration configuration, 
                               ILogger<LoginController> logger)
        {
            _configuration = configuration;
            _logger = logger;
        }
        /// <summary>
        /// 登录获取Token
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("login")]
        public async Task<string> GetUserTokenAsync(UserLoginDto input)
        {
            //输出日志
            _logger.LogInformation("用户登录");

            var client = new HttpClient();             //定义Http客户端
            var disco = await client.GetDiscoveryDocumentAsync(_configuration["AuthServer:Authority"]);

            var tokenClient = new TokenClient(client, new TokenClientOptions
            {
                Address = disco.TokenEndpoint,                        //访问Ids4的令牌地址
                ClientId = _configuration["AuthServer:AppId"],        //clientId
                ClientSecret = _configuration["AuthServer:AppSecret"] //clientSecret
            });

            var tokenResponse = await tokenClient.RequestPasswordTokenAsync(input.UserName, input.Password, "SmartTms");

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return string.Empty;
            }

            return tokenResponse.Json.ToString();
        }

    }
}
